package com;

import java.io.*;

public class FileUnit {
    private final static int LOGIN_ERROR_PASSWORD=-1;
    private final static int LOGIN_ERROR_NAME=0;
    private final static int LOGIN_SUCCESS=1;
    private final static int REGISTER_ERROR=-2;
    private final static int REGISTER_SUCCESS=2;

    public FileUnit() {

    }

    public static int finduser(String username, String password, String path, int flag){
        String result="";
        String line=null;
        try{
            BufferedReader br=new BufferedReader(new FileReader(path));
            while(result.equals("")&&(line=br.readLine())!=null){
                String[] arr=line.split(",");
                if(username.equals(arr[0])){
                    result=arr[1];
                }
            }
            br.close();
        }catch (Exception e){
            e.printStackTrace();
            return LOGIN_ERROR_PASSWORD;
        }
        if(result.equals("")&&flag==1)
            return LOGIN_ERROR_NAME;
        else if(!result.equals(password)&&flag==1)
            return LOGIN_ERROR_PASSWORD;
        else if(result.equals(password)&&flag==1)
            return LOGIN_SUCCESS;
        if(!result.equals("")&&flag==2){
            return REGISTER_ERROR;
        }
        else if(flag==2)
            return REGISTER_SUCCESS;
        return LOGIN_ERROR_PASSWORD;
    }
    public static int register(String username,String password,String path){
        if(username.equals(""))
            return REGISTER_ERROR;
        if(password.equals(""))
            return REGISTER_ERROR;
        int flag=-2;
        try {
            OutputStream os=new FileOutputStream(path,true);
            flag=finduser(username,password,path,2);
            if(flag==2){
                PrintWriter pw=new PrintWriter(os);
                pw.println(username+","+password);
                pw.close();
                os.close();
                return REGISTER_SUCCESS;
            }else {
                os.close();
                return REGISTER_ERROR;
            }
        }catch (Exception e){
            e.printStackTrace();
            return flag;
        }
    }
}
